﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using System.IO;
using CNotebook;
using CNotebook.Sales;
using CNotebook.Inventory;
using NotebookS2.Sales.Layouts;

namespace NotebookS2
{
    public partial class SalesDelivery : RibbonForm
    {
        public SalesDelivery()
        {
            InitializeComponent();
        }

        public bool UpdateDataOnStatus { get; set; }
        public Keys UsedKey = Keys.None;
        public int ObjectType { get { return 3; } }

        #region Properties
        public bool IsExportedFromSalesOrder { get; set; }
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public string DefaultWarehouse { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public DataTable DeliveryLineItems { get; set; }
        public DataTable AccountingEntries { get; set; }
        public double WithHoldingTaxRate { get; set; }
        public string DefaultPriceList { get; set; }
        public string VATCode { get; set; }
        public string VATRate { get; set; }
        public bool IsInclusive { get; set; }
        #endregion

        #region Initialization

        public void GetBusinessPartnerDefaults(string sCardCode)
        {
            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(sCardCode);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(sCardCode);

            txtPaymentTerms.Text = oBPManager.GetPaymentTerm(sCardCode);
            txtDivision.Text = oBPManager.GetDivision(sCardCode);
            oBPManager.Close();
            #endregion

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion
        }

        public string GetIsAutoDRConfig()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";

            if (File.Exists(sPath) == true)
            {
                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("AutoDR") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);

                            break;
                        }

                    }
                } while (input != null);

            }
            return _OUTPUT_STRING;

        }

        private static DataTable GetTable()
        {
            DataTable table = new DataTable();

            table.Columns.Add("ItemCode", typeof(string));
            table.Columns.Add("ItemDesc", typeof(string));
            table.Columns.Add("UoM", typeof(string));
            table.Columns.Add("QtyOrder", typeof(double));
            table.Columns.Add("CQtyOrder", typeof(double));
            table.Columns.Add("LotNumber", typeof(string));
            table.Columns.Add("LastStockQty", typeof(double));
            table.Columns.Add("Qty", typeof(double));
            table.Columns.Add("CQty", typeof(double));
            table.Columns.Add("PriceListCode", typeof(string));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("UnitCost", typeof(double));
            table.Columns.Add("IsFree", typeof(bool));
            table.Columns.Add("DiscPrcnt", typeof(double));
            table.Columns.Add("Discount", typeof(double));
            table.Columns.Add("TotalLineDisc", typeof(double));
            table.Columns.Add("Amount", typeof(double));
            table.Columns.Add("ItemGuID", typeof(string));
            
            return table;

        }

        private static DataTable GetGLAcctStructure()
        {
            DataTable table = new DataTable();

            table.Columns.Add("TransDate", typeof(DateTime));
            table.Columns.Add("TransType", typeof(string));
            table.Columns.Add("TransNum", typeof(string));
            
            table.Columns.Add("AcctCode", typeof(string));
            table.Columns.Add("AcctName", typeof(string));
            table.Columns.Add("Particulars", typeof(string));
            table.Columns.Add("DebitAmt", typeof(double));
            table.Columns.Add("CreditAmt", typeof(double));

            return table;

        }

        void InitializeSeries()
        {

            string ObjectType = this.ObjectType.ToString();
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            lblValidUntilDeliveryDate.Text = "Due Date:";
            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();
           
        }
        
        #endregion

        #region Functions / Methods

        double GetAvailableQuantity(string _ItemCode, string _Warehouse, string _LotNumber)
        {
            StockManager oManager = new StockManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            double _AvailableQty = oManager.GetAvailableQuantity(_Warehouse, _ItemCode, _LotNumber);

            oManager.Close();


            return _AvailableQty;
        }

        bool InComplete()
        {
            bool _Incomplete = false;

            if (txtDocumentNumber.Text == "") { return true; }
            if (txtCardCode.Text == "") { return true; }
            if (txtCardName.Text == "") { return true; }



            foreach (DataRow oRow in this.DeliveryLineItems.Rows)
            {
                if (oRow.RowState != DataRowState.Deleted)
                {
                    double _Qty = Convert.ToDouble(oRow["Qty"]);

                    if (_Qty == 0)
                    {
                        return true;
                    }
                }
            }

            return _Incomplete;

        }

        private void BindLotNumber(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            StockManager oManager = new StockManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

           
            DataTable _table = oManager.GetLotNumbers(sItemCode, cboLocation.EditValue.ToString());


            oManager.Close();

            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["LotNumber"].ToString());
            }



        }

        private void BindUoM(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            UoMManager oManager = new UoMManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetUnitMeasures(sItemCode);

            oManager.Close();

            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["UoM"].ToString());
            }

        }

        public string GetDiscountMethod()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";


            if (File.Exists(sPath) == true)
            {


                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("DiscountMethod") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);

                            break;
                        }

                    }
                } while (input != null);


            }
            return _OUTPUT_STRING;

        }
        
        public void CopyConsignmentToDelivery(string _ORDER_NO)
        {
            DateTime _NOW = System.DateTime.Now;

            InitializeSeries();                     // Initialize Series
            this.IsExportedFromSalesOrder = true;   // Indicator that it was imported from Sales Order

            dtPostDate.EditValue = _NOW;
            dtDeliveryDate.EditValue = _NOW;
            dtDocDate.EditValue = _NOW;

            BindWarehouse();                        // Binding the Combo Box Warehouse/Location
            BindSalesMan();                         // Binding Sales Man/Accounts
            BindCardDocument();
            //cboLocation.EditValue = this.DefaultWarehouse; // Setting the Default Warehouse of the User
            txtPaymentTerms.Text = "0";

            if (this.IsMultipleWarehouse == false)  // Enable the Selection of Combo Box if the Users Allowed to Select Multiple Warehouse
            {
                cboLocation.Enabled = false;
            }

            if (txtReference.Text != "")            // Reference Sales Order
            {
                return;
            }

            #region Intializing Issued Items Table and Line Items
            if (this.DeliveryLineItems == null)
            {
                this.DeliveryLineItems = GetTable();
            }

            gridDRItems.DataSource = this.DeliveryLineItems; // Line Items Data Table Binding in Grid
            gridDRItems.Refresh();

            if (gridViewDRItems.DataRowCount <= 0)
            {
                gridViewDRItems.AddNewRow();
            }

            #endregion

            ConsignmentManager oManager = new ConsignmentManager();

            #region Retrieving the Sales Order - Header


            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            txtReference.Text = _ORDER_NO;

            DataRow oHeaderRowSO = oManager.GetOrder(_ORDER_NO);

            cboLocation.EditValue = oHeaderRowSO["Destination"].ToString();
            txtStoreCode.Text = oHeaderRowSO["StoreCode"].ToString();
            txtCardCode.Text = oHeaderRowSO["CardCode"].ToString();
            txtCardName.Text = oHeaderRowSO["CardName"].ToString();
            txtBillTo.Text = oHeaderRowSO["BillTo"].ToString();
            txtShipTo.Text = oHeaderRowSO["ShipTo"].ToString();
            txtContactPerson.Text = oHeaderRowSO["ContactPerson"].ToString();
            cboSalesman.EditValue = oHeaderRowSO["SalesMan"].ToString();
            try
            {
                txtDisc1.Text = oHeaderRowSO["Discount1"].ToString();
                txtDisc2.Text = oHeaderRowSO["Discount2"].ToString();
                txtDisc3.Text = oHeaderRowSO["Discount3"].ToString();
                txtDisc4.Text = oHeaderRowSO["Discount4"].ToString();
            }
            catch
            {
            }
            this.VATCode = oHeaderRowSO["VATCode"].ToString();
            txtPaymentTerms.Text = oHeaderRowSO["PaymentTerms"].ToString();
            txtCustRefPO.Text = oHeaderRowSO["Reference"].ToString();
            #endregion

            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(txtCardCode.Text);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(txtCardCode.Text);

            txtPaymentTerms.Text = oBPManager.GetPaymentTerm(txtCardCode.Text);
            txtDivision.Text = oBPManager.GetDivision(txtCardCode.Text);
            oBPManager.Close();
            #endregion


            //dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion


            #region Importing the Sales Order Line Item to Delivery Line Items
            // Getting the Posted Order
            DataTable _TABLE_POSTED_ORDER = oManager.GetPostedOrder(txtReference.Text);

            //// INSERTING THE UNIQUE GuID
            //foreach (DataRow oRow in _TABLE_POSTED_ORDER.Rows)
            //{
            //    string _ItemGuID = System.Guid.NewGuid().ToString();
            //    oRow["ItemGuID"] = _ItemGuID;
            //}
            _TABLE_POSTED_ORDER.AcceptChanges();

            // Inserting the Line Items from Sales Order to Delivery Line Items
            if (_TABLE_POSTED_ORDER.Rows.Count > 0)
            {
                this.DeliveryLineItems = _TABLE_POSTED_ORDER;

                gridDRItems.DataSource = this.DeliveryLineItems;
                gridDRItems.Refresh();
                oManager.Close();
            }

            #endregion

            // Set up the Due Date based on the Terms
            DateTime _PostDate = (DateTime)dtPostDate.EditValue;

            dtDeliveryDate.EditValue = _PostDate.AddDays(Convert.ToInt16(txtPaymentTerms.Text));

            gridDRItems.DataSource = this.DeliveryLineItems;
            gridDRItems.Refresh();

            ComputeTotal();
            ApplyVolumeDiscount();

            if (GetIsAutoDRConfig() == "YES")
            {
                #region Checking if there are insufficient stocks unserved
                foreach (DataRow oRow in this.DeliveryLineItems.Rows)
                {
                    if (Convert.ToDouble(oRow["Qty"]) == 0)
                    {
                        MainMenu oMainMenu = (MainMenu)this.MdiParent;

                        oMainMenu.ErrMsg.Caption = oRow["ItemCode"].ToString().ToUpper() + " on-record stocks is insufficient!!!";
                        oMainMenu.ErrMsg.ImageIndex = 6;

                        oMainMenu.timer1.Enabled = true;
                    }
                }
                #endregion
            }
        }

        public void CopyOrderToDR(string _ORDER_NO)
        {
            DateTime _NOW = System.DateTime.Now;

            InitializeSeries();                     // Initialize Series
            this.IsExportedFromSalesOrder = true;   // Indicator that it was imported from Sales Order
            
            dtPostDate.EditValue        = _NOW;
            dtDeliveryDate.EditValue    = _NOW;
            dtDocDate.EditValue         = _NOW;

            BindWarehouse();                        // Binding the Combo Box Warehouse/Location
            BindSalesMan();                         // Binding Sales Man/Accounts
            BindCardDocument();
            
            txtPaymentTerms.Text = "0";
            
            if (this.IsMultipleWarehouse == false)  // Enable the Selection of Combo Box if the Users Allowed to Select Multiple Warehouse
            {
                cboLocation.Enabled = false;
            }            

            if (txtReference.Text != "")            // Reference Sales Order #
            {
                return;
            }

            #region Intializing Line Items Tables
           
            if (this.DeliveryLineItems == null)
            {
                this.DeliveryLineItems = GetTable();
            }

            gridDRItems.DataSource = this.DeliveryLineItems; // LINE ITEMS DATA TABLE BINDING IN GRID
            gridDRItems.Refresh();

            if (gridViewDRItems.DataRowCount <= 0)
            {
                gridViewDRItems.AddNewRow();
            }


            if (this.AccountingEntries == null)
            {
                this.AccountingEntries = GetGLAcctStructure();
            }

            gridDRAcctEntries.DataSource = this.AccountingEntries;
            gridDRAcctEntries.Refresh();
            if (gridViewDRAcctEntries.DataRowCount <= 0)
            {
                gridViewDRAcctEntries.AddNewRow();
            }

            #endregion

            #region Retrieving the Sales Order - Header
            OrderManager oManager = new OrderManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            txtReference.Text = _ORDER_NO;
            
            DataRow oHeaderRowSO = oManager.GetOrder(_ORDER_NO); //--<<>>--//

            cboLocation.EditValue = oHeaderRowSO["Location"].ToString();
            txtStoreCode.Text = oHeaderRowSO["StoreCode"].ToString();
            txtCardCode.Text = oHeaderRowSO["CardCode"].ToString();
            txtCardName.Text = oHeaderRowSO["CardName"].ToString();
            txtBillTo.Text = oHeaderRowSO["BillTo"].ToString();
            txtShipTo.Text = oHeaderRowSO["ShipTo"].ToString();
            txtContactPerson.Text = oHeaderRowSO["ContactPerson"].ToString();
            cboSalesman.EditValue = oHeaderRowSO["SalesMan"].ToString();
            try
            {
                txtDisc1.Text = oHeaderRowSO["Discount1"].ToString() ;
                txtDisc2.Text = oHeaderRowSO["Discount2"].ToString() ;
                txtDisc3.Text = oHeaderRowSO["Discount3"].ToString() ;
                txtDisc4.Text = oHeaderRowSO["Discount4"].ToString();
            }
            catch
            {
            }
            this.VATCode = oHeaderRowSO["VATCode"].ToString();
            txtPaymentTerms.Text = oHeaderRowSO["PaymentTerms"].ToString();
            txtCustRefPO.Text = oHeaderRowSO["Reference"].ToString();
            #endregion

            #region GETTING THE DEFAULT SETUP OF CUSTOMER IN MASTER FILE(ADDRESBOOK)
            
            //  GETTING THE CUSTOMER DEFAULT SETUP

            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();
            
            this.DefaultPriceList = oBPManager.GetPriceListCode(txtCardCode.Text);              // DEFAULT PRICELIST
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(txtCardCode.Text);       // WITHHOLDING TAX RATE
            txtPaymentTerms.Text = oBPManager.GetPaymentTerm(txtCardCode.Text);                 // PAYMENT TERMS
            txtDivision.Text = oBPManager.GetDivision(txtCardCode.Text);                        // DIVISION
            cboDocument.EditValue = oBPManager.GetDocument(txtCardCode.Text);                   // DOCUMENT CODE EITHER (INVOICE OR DELIVERY RECEIPT SERIES)

            oBPManager.Close();
            #endregion


            #region GETTING THE TAX CODE SETUP
            
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();                      //  VAT RATE CONFIGURATION
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;      //  IS VAT INCLUSIVE OR EXCLUSIVE SETUP
            

            #endregion


            #region IMPORTING THE SALES ORDER LINE ITEM TO DELIVERY LINE ITEMS
            // GETTING THE POSTED ORDER

            DataTable _TABLE_POSTED_ORDER = oManager.GetPostedOrder(txtReference.Text);
            _TABLE_POSTED_ORDER.AcceptChanges();

            // INSERTING THE LINE ITEMS FROM SALES ORDER TO DELIVERY LINE ITEMS
            if (_TABLE_POSTED_ORDER.Rows.Count > 0) 
            {
                this.DeliveryLineItems = _TABLE_POSTED_ORDER;

                gridDRItems.DataSource = this.DeliveryLineItems;
                gridDRItems.Refresh();
                oManager.Close();
            }

            #endregion

            // Set up the Due Date based on the Terms

            DateTime _PostDate = (DateTime)dtPostDate.EditValue;

            dtDeliveryDate.EditValue = _PostDate.AddDays(Convert.ToInt16(txtPaymentTerms.Text));
            
            gridDRItems.DataSource = this.DeliveryLineItems;
            gridDRItems.Refresh();
            
            ComputeTotal();
            ApplyVolumeDiscount();

        }

        public void PrintPreview()
        {
            PRNT_DLVRY oPrint = new PRNT_DLVRY();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;
            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }

        private void DisableControls()
        {
            cboLocation.Enabled = false;
            txtCardCode.Enabled = false;
            txtStoreCode.Enabled = false;
            txtCardName.Enabled = false;
            txtContactPerson.Enabled = false;
            txtReference.Enabled = false;
            txtCustRefPO.Enabled = false;
            txtBillTo.Enabled = false;
            txtShipTo.Enabled = false;
            txtDocumentNumber.Enabled = false;
            dtPostDate.Enabled = false;
            dtDeliveryDate.Enabled = false;
            dtDocDate.Enabled = false;
            cboDocument.Enabled = false;
            cboSalesman.Enabled = false;
            txtRemarks.Enabled = false;
            txtGrossAmount.Enabled = false;
            txtTotalLineDiscount.Enabled = false;
            txtDisc1.Enabled = false;
            txtDisc2.Enabled = false;
            txtDisc3.Enabled = false;
            txtDisc4.Enabled = false;
            txtTotalDiscount.Enabled = false;
            txtVAT.Enabled = false;
            txtNetAmt.Enabled = false;
            txtWithHoldingTax.Enabled = false;
            txtDivision.Enabled = false;
            txtRefDoc.Enabled = false;
            btnAdd.Enabled = false;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridViewDRItems.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = false;
            }

        }

        private void EnableControls()
        {
            if (this.IsMultipleWarehouse == true)
            {
                cboLocation.Enabled = true;
            }

            txtStoreCode.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtContactPerson.Enabled = true;
            txtReference.Enabled = true;
            txtCustRefPO.Enabled = true;
            txtBillTo.Enabled = true;
            txtShipTo.Enabled = true;
            txtDocumentNumber.Enabled = true;
            dtPostDate.Enabled = true;
            dtDeliveryDate.Enabled = true;
            dtDocDate.Enabled = true;

            txtRefDoc.Enabled = true;
            cboSalesman.Enabled = true;
            cboDocument.Enabled = true;
            txtRemarks.Enabled = true;
            txtGrossAmount.Enabled = true;
            txtTotalLineDiscount.Enabled = true;
            txtDisc1.Enabled = true;
            txtDisc2.Enabled = true;
            txtDisc3.Enabled = true;
            txtDisc4.Enabled = true;
            txtTotalDiscount.Enabled = true;
            txtVAT.Enabled = true;
            txtNetAmt.Enabled = true;
            txtWithHoldingTax.Enabled = false;
            btnAdd.Enabled = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridViewDRItems.Columns)
            {
                if (oColumn.Name == "Code" || oColumn.Name == "SrvdQty")
                {
                    oColumn.OptionsColumn.AllowEdit = true;
                }
            }

        }

        private string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = this.ObjectType.ToString();

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        private void ComputeTotal()
        {
            try
            {
                double _GrossAmount = 0;
                double _NetAmount = 0;
                double _LineDiscount = 0;

                foreach (DataRow oRow in this.DeliveryLineItems.Rows)
                {

                    if (oRow["Amount"] != DBNull.Value)
                    {
                        bool IsFree = false;
                        if (oRow["IsFree"] != DBNull.Value)
                        {
                            IsFree = Convert.ToBoolean(oRow["IsFree"]);
                        }
                        else
                        {
                            IsFree = false;
                        }


                        if (IsFree == false)
                        {
                            _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                            _NetAmount = _NetAmount + (Convert.ToDouble(oRow["Amount"]));
                            if (oRow["TotalLineDisc"] == DBNull.Value)
                            {
                                oRow["TotalLineDisc"] = 0;
                            }
                            _LineDiscount = _LineDiscount + (Convert.ToDouble(oRow["TotalLineDisc"]));
                        }
                    }
                }

                double _VAT = 0;

                double _VolumeDiscount = Convert.ToDouble(txtTotalDiscount.Text);


                if (this.VATCode == "VAT Inclusive")
                {
                    if (this.IsInclusive == true)
                    {

                        _VAT = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();

                        //txtWithHoldingTax.Text = Convert.ToString(((_NetAmount / Convert.ToDouble(this.VATRate)) * (this.WithHoldingTaxRate / 100)).ToString("##.00"));

                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }

                }

                if (this.VATCode == "VAT Exclusive")
                {
                    if (this.IsInclusive == false)
                    {
                        _VAT = _NetAmount * Convert.ToDouble(this.VATRate);
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();

                        //txtWithHoldingTax.Text = Convert.ToString((_NetAmount * (this.WithHoldingTaxRate / 100)).ToString("##.00"));
                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }
                }

                txtTotalLineDiscount.Text = _LineDiscount.ToString("#,###.00");
                txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");

                txtNetAmt.Text = _NetAmount.ToString("#,###.00");
                txtWithHoldingTax.Text = ((_NetAmount - _VolumeDiscount) * (this.WithHoldingTaxRate / 100)).ToString();



            }
            catch
            {
            }

        }

        private void ApplyVolumeDiscount()
        {

            double _GrossAmount = 0;
            double _NetAmount = 0;
            double _TotalLineDiscount = 0;
            double _VatAmount = 0;

            foreach (DataRow oRow in this.DeliveryLineItems.Rows)
            {

                if (oRow.RowState != DataRowState.Deleted)
                {
                    if (oRow["CQty"] == DBNull.Value)
                    {
                        oRow["CQty"] = 0;
                    }

                    if (oRow["Qty"] == DBNull.Value)
                    {
                        oRow["Qty"] = 0;
                    }
                    if (oRow["UnitPrice"] == DBNull.Value)
                    {
                        oRow["UnitPrice"] = 0;
                    }
                    if (oRow["TotalLineDisc"] == DBNull.Value)
                    {
                        oRow["TotalLineDisc"] = 0;
                    }
                    if (oRow["IsFree"] == DBNull.Value)
                    {
                        oRow["IsFree"] = false;
                    }
                    bool IsFree = Convert.ToBoolean(oRow["IsFree"]);

                    if (IsFree != true)
                    {
                        _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                        _TotalLineDiscount = _TotalLineDiscount + Convert.ToDouble(oRow["TotalLineDisc"]);
                    }
                }

            }

            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");


            string sDiscount1 = txtDisc1.Text.Replace("%", "");
            string sDiscount2 = txtDisc2.Text.Replace("%", "");
            string sDiscount3 = txtDisc3.Text.Replace("%", "");
            string sDiscount4 = txtDisc4.Text.Replace("%", "");


            double _disc1 = 0;
            double _disc2 = 0;
            double _disc3 = 0;
            double _disc4 = 0;


            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);

            double _TotalDiscount = 0;

            double _discount1 = 0;
            double _discount2 = 0;
            double _discount3 = 0;
            double _discount4 = 0;

            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);


            if (txtDisc4.Text == "")
            {
                _disc4 = 0;
            }
            else
            {
                _disc4 = Convert.ToDouble(sDiscount4);
            }

            if (_disc1 > 0)
            {
                _discount1 = (_GrossAmount - _TotalLineDiscount) * (_disc1 / 100);

                _TotalDiscount = (_GrossAmount - _TotalLineDiscount) - _discount1;
            }
            if (_disc2 > 0)
            {
                _discount2 = (_TotalDiscount * (_disc2 / 100));
                _TotalDiscount = _TotalDiscount - _discount2;

            }
            if (_disc3 > 0)
            {
                _discount3 = (_TotalDiscount * (_disc3 / 100));
                _TotalDiscount = _TotalDiscount - _discount3;
            }

            if (_disc4 > 0)
            {
                _discount4 = (_TotalDiscount * (_disc4 / 100));
                _TotalDiscount = _TotalDiscount - _discount4;
            }

            _TotalDiscount = (_discount1 + _discount2 + _discount3 + _discount4);
            txtTotalDiscount.Text = _TotalDiscount.ToString("#,###.00");



            txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");
            txtTotalLineDiscount.Text = _TotalLineDiscount.ToString("#,###.00");

            _NetAmount = (_GrossAmount - _TotalDiscount) - _TotalLineDiscount;


            string _DISCOUNT_METHOD = GetDiscountMethod();
            if (this.VATCode != "NON-VAT")
            {
                if (_DISCOUNT_METHOD == "After")
                {
                    if (this.VATCode == "VAT Inclusive")
                    {
                        _VatAmount = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                    }
                    else if (this.VATCode == "VAT Exclusive")
                    {
                        _VatAmount = _NetAmount * Convert.ToDouble(this.VATRate);
                        _NetAmount = _NetAmount + _VatAmount;
                    }
                }
                else
                {
                    if (this.VATCode == "VAT Inclusive")
                    {
                        _VatAmount = _GrossAmount - (_GrossAmount / Convert.ToDouble(this.VATRate));
                    }
                    else if (this.VATCode == "VAT Exclusive")
                    {
                        _VatAmount = _GrossAmount * Convert.ToDouble(this.VATRate);
                        _NetAmount = ((_GrossAmount + _VatAmount) - (_TotalDiscount - _TotalDiscount));
                    }
                }
            }




            txtVAT.Text = _VatAmount.ToString("#,###.00");
            txtNetAmt.Text = _NetAmount.ToString("#,###.00");
            txtWithHoldingTax.Text = (_NetAmount * (this.WithHoldingTaxRate / 100)).ToString();

            #region Returning Percent Sign
            if (_disc1 > 0)
            {
                txtDisc1.Text = _disc1.ToString("#.00") + "%";
            }
            else
            {
                txtDisc1.Text = "0%";
            }
            if (_disc2 > 0)
            {
                txtDisc2.Text = _disc2.ToString("#.00") + "%";
            }
            else
            {
                txtDisc2.Text = "0%";
            }
            if (_disc3 > 0)
            {
                txtDisc3.Text = _disc3.ToString("#.00") + "%";
            }
            else
            {
                txtDisc3.Text = "0%";
            }

            if (_disc4 > 0)
            {
                txtDisc4.Text = _disc4.ToString("#.00") + "%";
            }
            else
            {
                txtDisc4.Text = "0%";
            }
            #endregion


        }

        private void BindCardDocument()
        {
            CardDocumentManager oManager = new CardDocumentManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable dtDocuments = oManager.GetCardDocument();

            oManager.Close();

            cboDocument.Properties.Items.Clear();

            foreach (DataRow row in dtDocuments.Rows)
            {
                cboDocument.Properties.Items.Add(row["Code"]);
            }
        }

        private void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();
           

            cboLocation.Properties.DataSource = oTable;
            cboLocation.Properties.DisplayMember = "Dscription";
            cboLocation.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboLocation.Properties.Columns.Add(col);
            cboLocation.Properties.ShowHeader = false;
            
            oManager.Close();
        }

        void BindSalesMan()
        {
            AccountManager oManager = new AccountManager();
            DataTable oTable = new DataTable();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            oTable = oManager.GetAccounts("Salesman");
            cboSalesman.Visible = false;    
            cboSalesman.Properties.DataSource = oTable;
            cboSalesman.Properties.DisplayMember = "AccountHolder";
            cboSalesman.Properties.ValueMember = "AcctCode";

            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("AcctCode", "AcctName", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboSalesman.Refresh();
            cboSalesman.Visible = true;
            oManager.Close();

        }

        void RemoveBlankLastGLAccounts()
        {

            int iRowIndex = gridViewDRAcctEntries.RowCount;
            gridViewDRAcctEntries.FocusedRowHandle = iRowIndex - 1;
            try
            {
                string _AcctCode = "";


                if (gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]) != null)
                {
                    _AcctCode = gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]).ToString();
                }
                else
                {
                    _AcctCode = "";
                }

                if (_AcctCode.Trim() == "")
                {
                    gridViewDRAcctEntries.DeleteRow(gridViewDRAcctEntries.FocusedRowHandle);
                }
            }
            catch { }

        }

        void RemoveBlankLastRowFirst()
        {
            int iCount = -1;
            gridViewDRItems.MoveLast();
            try
            {
                int[] oRow = gridViewDRItems.GetSelectedRows();

                iCount = oRow[0];
                string sItemCode = "";


                sItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridViewDRItems.DeleteRow(iCount);
                    this.DeliveryLineItems.AcceptChanges();
                }
            }
            catch { }

        }

        void CancelOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to cancel this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                DeliveryManager oManager = new DeliveryManager();
                DeliveryUnit oUnit = new DeliveryUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.DocumentCode = cboDocument.Text;
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                
                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateDelivery(oUnit);
                oManager.Close();
                #endregion
                if (UpdateDataOnStatus == false)
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 8;
                    oForm.ErrMsg.Caption = "Updating document is successfull!!!";
                    oForm.timer1.Enabled = true;
                    //MessageBox.Show("Updating document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    UpdateDataOnStatus = true;
                }
                #endregion

                oManager = new DeliveryManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CancelDR(sDocNumber, this.ActiveUserID);
                oManager.Close();


                OrderManager oOrderManager = new OrderManager();
                //Back to order
                oOrderManager.ConnectionString = this.ConnectionString;
                oOrderManager.Open();
                oOrderManager.PostOrder(txtReference.Text);
                oOrderManager.Close();

                txtStatus.Text = "Canceled";
            }

        }

        void ChangeToDeliverStatus(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to deliver this order?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                DeliveryManager oManager = new DeliveryManager();
                DeliveryUnit oUnit = new DeliveryUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.DocumentCode = cboDocument.Text;

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateDelivery(oUnit);
                oManager.Close();
                #endregion

                if (UpdateDataOnStatus == false)
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 8;
                    oForm.ErrMsg.Caption = "Updating document is successfull!!!";
                    oForm.timer1.Enabled = true;
                    //MessageBox.Show("Updating document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    UpdateDataOnStatus = true;
                }
                #endregion

                oManager = new DeliveryManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.DeliverOrder(cboLocation.EditValue.ToString(), txtReference.Text, sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Delivered";


            }
        }

        void ChangeToPostedStatus(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to post this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                DeliveryManager oManager = new DeliveryManager();
                DeliveryUnit oUnit = new DeliveryUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.DocumentCode = cboDocument.Text;
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateDelivery(oUnit);
                oManager.Close();
                #endregion

             
                #endregion

                oManager = new DeliveryManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.PostDocument(sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Posted";
            }
        }

        void ChangeToClosedStatus(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to close this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                #region Update Invoice
                DeliveryManager oManager = new DeliveryManager();
                DeliveryUnit oUnit = new DeliveryUnit();

                #region Header Sales Delivery

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.CustRefPO = txtCustRefPO.Text;
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }


                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.Division = txtDivision.Text;
                oUnit.DocumentCode = cboDocument.Text;
                oUnit.DivReference = txtRefDoc.Text;
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.DeliveryLineItems;
                
                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateDelivery(oUnit);
                oManager.Close();
                #endregion
                
                #endregion

                oManager = new DeliveryManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CloseDR(sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Closed";

            }
        }

        public void ShowSearch()
        {
            FND_DLVRY oSearchDocument = new FND_DLVRY();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                DeliveryManager oManager = new DeliveryManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetDelivery(sDocumentNumber);


                #region Header
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
                dtDeliveryDate.EditValue = (DateTime)oRow["DueDate"];
                dtDocDate.EditValue = (DateTime)oRow["DocDate"];

                txtStoreCode.Text = oRow["StoreCode"].ToString();
                txtCardCode.EditValue = oRow["CardCode"].ToString();
                

                AddressBookManager oCardManager = new AddressBookManager();
                oCardManager.Connection = oManager.Connection;
                this.DefaultPriceList = oCardManager.GetPriceListCode(txtCardCode.Text);
                txtCardName.EditValue = oRow["CardName"].ToString();
                txtContactPerson.EditValue = oRow["ContactPerson"].ToString();
                txtPaymentTerms.Text = oRow["PaymentTerms"].ToString();

                txtReference.EditValue = oRow["Reference"].ToString();
                txtCustRefPO.EditValue = oRow["CustRefPO"].ToString();
                txtBillTo.EditValue = oRow["BillTo"].ToString();
                txtShipTo.EditValue = oRow["ShipTo"].ToString();
                cboSalesman.EditValue = oRow["SalesMan"].ToString();
                txtRemarks.EditValue = oRow["Remarks"].ToString();
                txtDivision.EditValue = oRow["Division"].ToString();
                cboDocument.EditValue = oRow["DocumentCode"].ToString();
                txtRefDoc.EditValue = oRow["DivReference"].ToString();
                cboLocation.EditValue = oRow["Location"].ToString();
                


                //if (oRow["Location"] != DBNull.Value)
                //{
                    
                //}
                if (oRow["VATCode"] != DBNull.Value)
                {
                    this.VATCode = oRow["VATCode"].ToString();
                }

                this.VATRate = oRow["VATRate"].ToString();

                if (oRow["IsVATInclusive"] != DBNull.Value)
                {

                    if (oRow["IsVATInclusive"].ToString() == "Y")
                    {
                        this.IsInclusive = true;
                    }
                    else
                    {
                        this.IsInclusive = false;
                    }
                }

                txtGrossAmount.EditValue = oRow["GrossAmount"].ToString();
                txtVAT.EditValue = oRow["VATAmount"].ToString();
                txtDisc1.EditValue = oRow["Discount1"].ToString();
                txtDisc2.EditValue = oRow["Discount2"].ToString();
                txtDisc3.EditValue = oRow["Discount3"].ToString();
                txtDisc4.EditValue = oRow["Discount4"].ToString();
                txtTotalDiscount.EditValue = oRow["TotalDiscount"].ToString();
                txtNetAmt.EditValue = oRow["NetAmount"].ToString();
                txtWithHoldingTax.Text = oRow["WithHoldingTax"].ToString();
                //oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                #endregion

                #region Line Items
                this.DeliveryLineItems = oManager.GetDeliveryLineItems(sDocumentNumber);
                gridDRItems.DataSource = this.DeliveryLineItems;
                gridDRItems.Refresh();
                #endregion

                #region Distributed Accounts
                this.AccountingEntries = oManager.GetAccountingDistribution(sDocumentNumber);

                gridDRAcctEntries.DataSource = this.AccountingEntries;
                gridDRAcctEntries.Refresh();
                #endregion

                if (txtStatus.Text == "Draft")
                {
                    if (gridViewDRItems.RowCount == 0)
                    {
                        gridViewDRItems.AddNewRow();
                    }
                }

                oManager.Close();

                btnAdd.Text = "Ok";
                GetBusinessPartnerDefaults(txtCardCode.Text);
                ComputeTotal();
                ApplyVolumeDiscount();
                txtDocumentNumber.Enabled = false;



            }

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(null, null);
            }
        }

        #endregion

        #region Access Code

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }

        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;
            btnCopyToSR.Enabled = false;

            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;
            btnCopyToSR.Enabled = true;
            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }


        #endregion

        #region FORM/CONTROL EVENTS

        private void SalesDelivery_Load(object sender, EventArgs e)
        {
            if (IsExportedFromSalesOrder == false)
            {
                BindWarehouse();
                BindCardDocument();

                cboLocation.EditValue = this.DefaultWarehouse;
                if (this.IsMultipleWarehouse == false)
                {
                    cboLocation.Enabled = false;
                }

                BindSalesMan();
                InitializeSeries();

                if (txtReference.Text != "")
                {
                    return;
                }

                dtPostDate.EditValue = System.DateTime.Now;
                dtDeliveryDate.EditValue = System.DateTime.Now;
                dtDocDate.EditValue = System.DateTime.Now;
                txtPaymentTerms.Text = "0";

                #region Details
                if (this.DeliveryLineItems == null)
                {
                    this.DeliveryLineItems = GetTable();
                }

                gridDRItems.DataSource = this.DeliveryLineItems;
                gridDRItems.Refresh();

                if (gridViewDRItems.DataRowCount <= 0)
                {
                    gridViewDRItems.AddNewRow();
                }
                #endregion
                
                #region GL Accounts
                if (this.AccountingEntries == null)
                {
                    this.AccountingEntries = GetGLAcctStructure();
                }

                gridDRAcctEntries.DataSource = this.AccountingEntries;
                gridDRAcctEntries.Refresh();

                if (gridViewDRAcctEntries.DataRowCount <= 0)
                {
                    gridViewDRAcctEntries.AddNewRow();
                }
                #endregion

            }
            
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            string _USR_AUTHORIZATION = ApplyAuthorization();

            try
            {
                string _ITEM_CODE = gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();
                BindLotNumber(_ITEM_CODE, cboLotNumber);
            }
            catch
            {
                //
            }

            if (_USR_AUTHORIZATION == "No Access" || _USR_AUTHORIZATION == "Read Only")
            {
                return;
            }

            try
            {
                int iCount = gridViewDRItems.FocusedRowHandle;

                if (e.KeyCode == Keys.Delete)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (gridViewDRItems.IsLastRow)
                        {
                            string sItemCode = "";

                            iCount = gridViewDRItems.FocusedRowHandle;

                            sItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                           
                            if (sItemCode != "")
                            {
                                gridViewDRItems.DeleteRow(iCount);
                                gridViewDRItems.AddNewRow();
                            }
                        }
                        else
                        {
                            string sItemCode = "";

                            iCount = gridViewDRItems.FocusedRowHandle;
                            sItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();

                            if (sItemCode != "")
                            {
                                gridViewDRItems.DeleteRow(iCount);
                            }

                            gridViewDRItems.RefreshData();
                        }

                        ComputeTotal();
                    }
                }
                
                if (e.KeyCode == Keys.Down)
                {
                    if (gridViewDRItems.IsLastRow)
                    {
                        string sItemCode = "";
                        iCount = gridViewDRItems.FocusedRowHandle;

                        sItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();

                        if ((sItemCode != "" && (txtStatus.Text == "Draft" || txtStatus.Text == "Open")))
                        {
                            gridViewDRItems.AddNewRow();

                            gridViewDRItems.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                            gridViewDRItems.FocusedColumn = gridViewDRItems.VisibleColumns[0];
                            gridViewDRItems.ShowEditor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void txtSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
         
            string  _ItemGuID   = System.Guid.NewGuid().ToString();
            int iRowIndex       = gridViewDRItems.FocusedRowHandle;
            
            FND_ITM_SO _FORM_SEARCH_ITEM = new FND_ITM_SO();

            _FORM_SEARCH_ITEM.ConnectionString  = this.ConnectionString;
            _FORM_SEARCH_ITEM.CustomerCode      = this.txtCardCode.Text;          
  
            #region Adding Added Item Codes in SEARCH FORM

            foreach (DataRow oRows in this.DeliveryLineItems.Rows)
            {
                _FORM_SEARCH_ITEM.ItemCodes.Add(oRows["ItemCode"].ToString());
            }

            #endregion


            _FORM_SEARCH_ITEM.ShowDialog();


            if (_FORM_SEARCH_ITEM.ItemCode != null)
            {
                if (_FORM_SEARCH_ITEM.ItemCode.Trim() != "")
                {
                    int _unitMeasureCount = 0;
                    double _PackSize = 1;
                    string _unitMeasure = "";
                    double _OrderQty = 0;

                    #region Binding Unit Measures in Grid
                    UoMManager oUnitMeasureManager          = new UoMManager();
                    
                    oUnitMeasureManager.ConnectionString    = this.ConnectionString;
                    oUnitMeasureManager.Open();
                    
                    BindUoM(_FORM_SEARCH_ITEM.ItemCode, cboUnitMeasure);
                    _unitMeasureCount = cboUnitMeasure.Items.Count;

                    if (_unitMeasureCount > 0)
                    {
                        _unitMeasure    = _FORM_SEARCH_ITEM.UOM;
                        _PackSize       = oUnitMeasureManager.GetPackSize(_FORM_SEARCH_ITEM.ItemCode, _unitMeasure);
                    }

                    oUnitMeasureManager.Close();
                    #endregion

                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["ItemCode"], _FORM_SEARCH_ITEM.ItemCode);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["ItemDesc"], _FORM_SEARCH_ITEM.Description);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UoM"], _FORM_SEARCH_ITEM.UOM);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UnitPrice"], _FORM_SEARCH_ITEM.UnitPrice);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["IsFree"], false);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["QtyOrder"], _OrderQty);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["CQtyOrder"], 1);
                    
                    if (Convert.ToDouble(this.VATRate) == 0)
                    {
                        gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UnitPrice"], _FORM_SEARCH_ITEM.UnitPrice);
                        
                    }
                    else
                    {

                        gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UnitPrice"], _FORM_SEARCH_ITEM.UnitPrice);
                        
                    }

                    int _ZeroVAL = 0;
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["DiscPrcnt"], _ZeroVAL);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["Discount"], _ZeroVAL);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["TotalDiscount"], _ZeroVAL);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["ItemGuID"], _ItemGuID);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UoM"], _FORM_SEARCH_ITEM.UOM);


                    #region Applying in Line Item Amount Computation

                    double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iRowIndex, gridViewDRItems.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = 0 * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iRowIndex, gridViewDRItems.Columns["Discount"]).ToString());

                    double _AMOUNT = (0 * _UNITPRICE) - _TOTAL_DISCOUNT;
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["Amount"], _AMOUNT);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                    #endregion

                    BindLotNumber(_FORM_SEARCH_ITEM.ItemCode, cboLotNumber);

                }
                else
                {
                    gridViewDRItems.CancelUpdateCurrentRow();
                    if (gridViewDRItems.RowCount <= 0)
                    {
                        gridViewDRItems.AddNewRow();
                    }
                }
            }
            else
            {
                gridViewDRItems.CancelUpdateCurrentRow();
                if (gridViewDRItems.RowCount <= 0)
                {
                    gridViewDRItems.AddNewRow();
                }
            }

            _FORM_SEARCH_ITEM.Dispose();
        }

        private void txtSearchItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            this.UsedKey = e.KeyCode;

            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
            {
                #region New Code From Sales Order
                string _ItemGUID = System.Guid.NewGuid().ToString();

                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                try
                {
                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["UNITOFMEASURE"].ToString(),
                                        UnitPrice = row["UNITPRICE"].ToString()
                                    };


                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                        double _ZeroVAL = 0;
                        int iRowIndex = gridViewDRItems.FocusedRowHandle;
                        int iCountQty = 0;

                        try
                        {
                            iCountQty = Convert.ToInt32(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        foreach (var oUnit in items)
                        {
                            BindUoM(oUnit.ItemCode, cboUnitMeasure);
                            BindLotNumber(oUnit.ItemCode, cboLotNumber);
                            int _unitMeasureCount = 0;
                            double _PackSize = 0;
                            string _unitMeasure = "";

                            UoMManager oUnitMeasureManager = new UoMManager();
                            oUnitMeasureManager.ConnectionString = this.ConnectionString;
                            oUnitMeasureManager.Open();
                            _unitMeasureCount = cboUnitMeasure.Items.Count;

                            if (_unitMeasureCount > 0)
                            {
                                _unitMeasure = oUnit.UoM;
                                _PackSize = oUnitMeasureManager.GetPackSize(oUnit.ItemCode, _unitMeasure);
                            }

                            oUnitMeasureManager.Close();
                            gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["ItemCode"], oUnit.ItemCode);
                            gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["ItemDesc"], oUnit.Dscription);

                            if (IsExportedFromSalesOrder == false || iCountQty == 0)
                            {

                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["QtyOrder"], 0);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["CQtyOrder"], _PackSize);

                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["Qty"], 0);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["CQty"], _PackSize);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UoM"], oUnit.UoM);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["UnitPrice"], oUnit.UnitPrice);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["Discount"], _ZeroVAL);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["DiscPrcnt"], _ZeroVAL);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["Discount"], _ZeroVAL);
                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["TotalLineDisc"], _ZeroVAL);

                                gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["ItemGuID"], _ItemGUID);
                            }
                        }
                        #endregion



                        try
                        {
                            string _ITEM_CODE = gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();

                            BindLotNumber(_ITEM_CODE, cboLotNumber);


                        }
                        catch
                        {
                            //
                        }

                        int iQtyServed = 0;
                        try
                        {
                            iQtyServed = Convert.ToInt16(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        int iCQtyServed = 0;
                        try
                        {
                            iCQtyServed = Convert.ToInt16(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["CQty"]));
                        }
                        catch
                        {
                        }



                        #region Applying in Line Item Amount Computation
                        double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iRowIndex, gridViewDRItems.Columns["UnitPrice"]).ToString());
                        double _TOTAL_DISCOUNT = (iQtyServed * iCQtyServed) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iRowIndex, gridViewDRItems.Columns["Discount"]).ToString());

                        double _AMOUNT = ((iQtyServed * iCQtyServed) * _UNITPRICE) - _TOTAL_DISCOUNT;
                        gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridViewDRItems.SetRowCellValue(iRowIndex, gridViewDRItems.Columns["Amount"], _AMOUNT);

                        ComputeTotal();
                        ApplyVolumeDiscount();
                        #endregion


                        gridViewDRItems.FocusedColumn = gridViewDRItems.Columns["Qty"];
                        SendKeys.Send("{ENTER}");
                        return;

                    }
                    else
                    {

                        if (!(this.UsedKey == Keys.Escape))
                        {


                            if (sItemCode.Trim() != "")
                            {
                                MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                gridViewDRItems.FocusedColumn = gridViewDRItems.Columns["ItemCode"];

                                SendKeys.Send("{ENTER}");

                                return;
                            }
                            this.UsedKey = Keys.None;
                        }
                        else
                        {
                            this.UsedKey = Keys.None;
                        }
                    }
                }
                catch
                {
                }
                #endregion
            }

            #region Disabled Code
            //if (e.KeyCode == Keys.Enter)
            //{
            //    try
            //    {
            //        DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;


            //        string sItemCode = oButtonEdit.Text;

            //        ItemManager oManager = new ItemManager();

            //        oManager.ConnectionString = this.ConnectionString;
            //        oManager.Open();

            //        DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

            //        oManager.Close();

            //        if (dt.Rows.Count > 0)
            //        {
            //            var items = from row in dt.AsEnumerable() 
            //                        select new
            //                        {
            //                            ItemCode = row["ItemCode"].ToString(),
            //                            Dscription = row["Description"].ToString(),
            //                            UoM = row["UNITOFMEASURE"].ToString(),
            //                            UnitPrice = row["UNITPRICE"].ToString()
            //                        };


            //            int iCount = -1;
            //            int[] oRow = gridView1.GetSelectedRows();

            //            iCount = oRow[0];

            //            string sVAT = this.VATCode.Trim() !="" ? this.VATCode : "N/A";

            //            foreach (var oUnit in items)
            //            {
            //                string _ItemGuID2 = System.Guid.NewGuid().ToString();
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
            //                double _OrderQty = 0;
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["QtyOrder"], _OrderQty);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], false);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["GrossPrice"], oUnit.UnitPrice);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["NetPrice"], oUnit.UnitPrice);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], 0);
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGuID2);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["VatCode"], sVAT);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["VatRate"], this.VATRate);
            //                //gridView1.SetRowCellValue(iCount, gridView1.Columns["VatApld"], 0);
            //            }
            //        }
            //    }
            //    catch
            //    {
            //    }
            //}
            #endregion
        }

        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void txtLineDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = gridViewDRItems.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtLineDiscount = (DevExpress.XtraEditors.TextEdit)sender;

                double _lineDiscount = Convert.ToDouble(oTxtLineDiscount.Text);
                double _UnitPrice = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString());
                double _Percentage = 0;

                _Percentage = _lineDiscount / _UnitPrice;

                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["DiscPrcnt"], (_Percentage * 100));
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], (_Qty * _CQty) * _lineDiscount);

                double _TotalDiscount = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"]).ToString());

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;
                
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _Amount);

                ComputeTotal();

            }
        }

        private void txtLineDiscPercent_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = gridViewDRItems.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt/100);
                double _TotalDiscount = (_Qty *_CQty) * _LineDiscount;

                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Discount"], _LineDiscount);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;
                
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _Amount);

                ComputeTotal();
                
            }
        }
      
        private void btnAdd_Click(object sender, EventArgs e)
        {
            RemoveBlankLastRowFirst();
            foreach (DataRow oRow in this.DeliveryLineItems.Rows)
            {
                if (oRow.RowState != DataRowState.Deleted)
                {
                    if (oRow["LotNumber"] == DBNull.Value)
                    {
                        MessageBox.Show("Please select Batch/Lot Number!!!", "Lot Number", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    if (oRow["LotNumber"].ToString().Trim() == "")
                    {
                        MessageBox.Show("Please select Batch/Lot Number!!!", "Lot Number", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }


                    if (oRow["Qty"] == DBNull.Value)
                    {
                        MessageBox.Show("Please insert Quantity!!!", "Quantity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    if (oRow["Qty"].ToString().Trim() == "")
                    {
                        MessageBox.Show("Please insert Quantity!!!", "Quantity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
            }
            
            
            DeliveryManager oManager = new DeliveryManager();
            DeliveryUnit oUnit = new DeliveryUnit();
            
            RemoveBlankLastRowFirst();
            
            if (InComplete() == false)
            {
                
                if (btnAdd.Text == "Add")
                {

                    #region Header - Sales Delivery

                    txtDocumentNumber.Text = GetNewSeries();
                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    oUnit.StoreCode = txtStoreCode.Text;
                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.ContactPerson = txtContactPerson.Text;
                    oUnit.PaymentTerms = txtPaymentTerms.Text;

                    oUnit.Reference = txtReference.Text;
                    oUnit.CustRefPO = txtCustRefPO.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    oUnit.BillTo = txtBillTo.Text;
                    oUnit.Location = cboLocation.EditValue.ToString();
                    
                    if (cboSalesman.EditValue != null)
                    {
                        oUnit.SalesMan = cboSalesman.EditValue.ToString();
                    }
                    else
                    {
                        oUnit.SalesMan = "";
                    }

                    oUnit.Remarks = txtRemarks.Text;

                    oUnit.TaxCode = this.VATCode.ToString();
                    oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                    if (oUnit.TaxCode != "NON-VAT")
                    {
                        oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                    }
                    else
                    {
                        oUnit.IsVATInclusive = "N/A";
                    }



                    oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                    oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                    oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                    oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                    oUnit.Discount1 = txtDisc1.Text;
                    oUnit.Discount2 = txtDisc2.Text;
                    oUnit.Discount3 = txtDisc3.Text;
                    oUnit.Discount4 = txtDisc4.Text;

                    oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                    oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                    oUnit.Division = txtDivision.Text;
                    oUnit.DocumentCode = cboDocument.Text;
                    oUnit.DivReference = txtRefDoc.Text;

                    oUnit.CreatedBy = this.ActiveUserID;
                    oUnit.ModifiedBy = this.ActiveUserID;

                    #endregion

                    oUnit.LineItems = this.DeliveryLineItems;
                    oUnit.AccountingEntries = this.AccountingEntries;
                    
                    if (txtDocumentNumber.Text.Trim() != "")
                    {
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        if (oManager.IsDocumentExists(txtDocumentNumber.Text) == false)
                        {
                            if (txtRefDoc.Text != "")
                            {
                                if (oManager.IsReferenceSIDRNoExists(cboDocument.EditValue.ToString(), txtRefDoc.Text) == false)
                                {
                                    #region Adding Portion

                                    System.Data.SqlClient.SqlException SqlEx = oManager.AddDelivery(oUnit);

                                    if (SqlEx == null)
                                    {
                                        txtDocumentNumber.Enabled = false;
                                        OrderManager _SALES_ORDER_MANAGER = new OrderManager();

                                        _SALES_ORDER_MANAGER.Connection = oManager.Connection;
                                        _SALES_ORDER_MANAGER.SetOrderInProcess(txtReference.Text);


                                        btnAdd.Text = "Ok";
                                        MessageBox.Show("Adding document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    }
                                    else
                                    {
                                        MessageBox.Show(SqlEx.Message, "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    #endregion
                                }
                                else
                                {

                                    MessageBox.Show("SI/DR Document reference is already exist in the record! Please try another document number then save it again!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    txtRefDoc.Focus();
                                    txtRefDoc.SelectAll();

                                }
                            }
                            else
                            {
                                #region Adding Portion

                                System.Data.SqlClient.SqlException SqlEx = oManager.AddDelivery(oUnit);

                                if (SqlEx == null)
                                {
                                    txtDocumentNumber.Enabled = false;
                                    OrderManager _SALES_ORDER_MANAGER = new OrderManager();

                                    _SALES_ORDER_MANAGER.Connection = oManager.Connection;
                                    _SALES_ORDER_MANAGER.SetOrderInProcess(txtReference.Text);


                                    btnAdd.Text = "Ok";
                                    MessageBox.Show("Adding document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                }
                                else
                                {
                                    MessageBox.Show(SqlEx.Message, "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                #endregion
                            }
                                
                        }
                        else
                        {
                            MessageBox.Show("Document is already exist in the record! Please try another document number then save it again!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            txtDocumentNumber.Focus();
                            txtDocumentNumber.SelectAll();
                        }
                        oManager.Close();

                    }
                    else
                    {
                        MessageBox.Show("Please enter document number!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtDocumentNumber.Focus();
                        txtDocumentNumber.SelectAll();
                    }


                }
                else if (btnAdd.Text == "Update")
                {

                    #region Header Sales Delivery

                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    oUnit.CustRefPO = txtCustRefPO.Text;
                    oUnit.StoreCode = txtStoreCode.Text;
                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.ContactPerson = txtContactPerson.Text;
                    oUnit.Reference = txtReference.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    oUnit.BillTo = txtBillTo.Text;
                    oUnit.Location = cboLocation.EditValue.ToString();

                    if (cboSalesman.EditValue != null)
                    {
                        oUnit.SalesMan = cboSalesman.EditValue.ToString();
                    }
                    else
                    {
                        oUnit.SalesMan = "";
                    }

                    oUnit.Remarks = txtRemarks.Text;

                    oUnit.TaxCode = this.VATCode.ToString();
                    oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                    if (oUnit.TaxCode != "NON-VAT")
                    {
                        oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                    }
                    else
                    {
                        oUnit.IsVATInclusive = "N/A";
                    }


                    oUnit.PaymentTerms = txtPaymentTerms.Text;
                    oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                    oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());

                    oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                    oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                    oUnit.Discount1 = txtDisc1.Text;
                    oUnit.Discount2 = txtDisc2.Text;
                    oUnit.Discount3 = txtDisc3.Text;
                    oUnit.Discount4 = txtDisc4.Text;

                    oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                    oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                    oUnit.Division = txtDivision.Text;
                    oUnit.DocumentCode = cboDocument.Text;
                    oUnit.DivReference = txtRefDoc.Text;

                    oUnit.ModifiedBy = this.ActiveUserID;
                    #endregion

                    oUnit.LineItems = this.DeliveryLineItems;
                    
                    #region Updating Portion
                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();
                    System.Data.SqlClient.SqlException SqlEx = oManager.UpdateDelivery(oUnit);
                    oManager.Close();
                    #endregion

                    if (SqlEx == null)
                    {
                        if (UpdateDataOnStatus == false)
                        {
                            MessageBox.Show("Updating document is successfull!!!", "Sales Invoice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            UpdateDataOnStatus = true;
                        }

                        btnAdd.Text = "Ok";
                    }
                    else
                    {
                        MessageBox.Show(SqlEx.Message.ToString(), "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    this.Close();
                }

            }
            else
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Please complete the required information, zero value in the quantity is also not allowed in the Line Items!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Please complete the required information, zero value in the quantity is also not allowed in the Line Items!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc1.Text.Trim() != "0%" && txtDisc1.Text.Trim() != "" && txtDisc1.Text.Trim() != ".00%" && txtDisc1.Text.Trim() != "0" && txtDisc1.Text.Trim() != ".00")
            {
                txtDisc2.Enabled = true;
            }
            else
            {
                txtDisc2.Enabled = false;
                txtDisc2.Text = "0%";
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc2_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc2.Text.Trim() != "0%" && txtDisc2.Text.Trim() != "" && txtDisc2.Text.Trim() != ".00%" && txtDisc2.Text.Trim() != "0" && txtDisc2.Text.Trim() != ".00")
            {
                txtDisc3.Enabled = true;
            }
            else
            {
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc3_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".00%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".00")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc4_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".00%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".00")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDiscount_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc1.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc1.Text = string.Format("{0:###.00}", txtDisc1.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc1.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc1.Text = "0%";
            }
        }

        private void txtDisc2_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc2.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc2.Text = string.Format("{0:###.00}", txtDisc2.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc2.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc2.Text = "0%";
            }
        }

        private void txtDisc3_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc3.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc3.Text = string.Format("{0:###.00}", txtDisc3.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc3.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc3.Text = "0%";
            }
        }

        private void txtDisc4_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCheck = Convert.ToInt16(txtDisc4.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc4.Text = string.Format("{0:###.00}", txtDisc4.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc4.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc4.Text = "0%";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gridViewDR_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
            ApplyVolumeDiscount();


            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }

            
        }

        private void txtDiscount_Enter(object sender, EventArgs e)
        {
            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
        }

        private void txtDisc2_Enter(object sender, EventArgs e)
        {
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
        }

        private void txtDisc3_Enter(object sender, EventArgs e)
        {
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
        }

        private void txtDisc4_Enter(object sender, EventArgs e)
        {
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");
        }

        private void txtDiscount_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc2_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc3_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc4_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }
        
        private void chkFree_CheckedChanged(object sender, EventArgs e)
        {
            int iCount = -1;
            int[] oRow = gridViewDRItems.GetSelectedRows();
            
            iCount = oRow[0];
            DevExpress.XtraEditors.CheckEdit oCheckBox = (DevExpress.XtraEditors.CheckEdit)sender;

            bool IsChecked = oCheckBox.Checked;
            int _ZeroVAL = 0;

            if (IsChecked == true)
            {
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["DiscPrcnt"], _ZeroVAL);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Discount"], _ZeroVAL);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _ZeroVAL);
                
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _ZeroVAL);
            }
            else
            {
                string sItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                double dNetPrice = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                double iQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString());
                double CQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString());
                
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["DiscPrcnt"], _ZeroVAL);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Discount"], _ZeroVAL);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _ZeroVAL);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], (iQty * CQty) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"])));
            }
        }

        private void txtReference_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            if (txtStatus.Text == "Posted" || txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                return;
            }
            FND_REFERENCE_SO _SEARCH_REFERENCE_ORDER = new FND_REFERENCE_SO();

            if (cboLocation.EditValue == null)
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Please select warehouse!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Please select warehouse!!!", "Warehouse", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cboLocation.Focus();
                return;
            }


            if (txtCardCode.Text != "")
            {
                _SEARCH_REFERENCE_ORDER.ConnectionString = this.ConnectionString;
                _SEARCH_REFERENCE_ORDER.CardCode = txtCardCode.Text;

                _SEARCH_REFERENCE_ORDER.ShowDialog();

                if (_SEARCH_REFERENCE_ORDER.SalesOrderNumber == null)
                {
                    return;
                }

                if (_SEARCH_REFERENCE_ORDER.SalesOrderNumber.Trim() == "")
                {
                    return;
                }

                txtReference.Text = _SEARCH_REFERENCE_ORDER.SalesOrderNumber;

                

                OrderManager oManager = new OrderManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();


                DataRow oHeaderRowSO = oManager.GetOrder(txtReference.Text);

                txtPaymentTerms.Text = oHeaderRowSO["PaymentTerms"].ToString();


                DataTable _TABLE = oManager.GetPostedOrder(txtReference.Text);

                if (_TABLE.Rows.Count > 0)
                {
                    this.DeliveryLineItems = _TABLE;

                    gridDRItems.DataSource = this.DeliveryLineItems;
                    gridDRItems.Refresh();
                    oManager.Close();
                }

                CNotebook.Inventory.StockManager oStockManager = new CNotebook.Inventory.StockManager();


                #region Line Items
                foreach (DataRow oRow in this.DeliveryLineItems.Rows)
                {
                    DataTable _STOCK_CARD = new DataTable();
                    oStockManager = new StockManager();
                    oStockManager.ConnectionString = this.ConnectionString;
                    oStockManager.Open();

                    _STOCK_CARD = oStockManager.GetAvailableStockByItemCode(this.cboLocation.EditValue.ToString(), oRow["ItemCode"].ToString());

                    double _PackSize = Convert.ToDouble(oRow["CQtyOrder"]);
                    double _Order = Convert.ToDouble(oRow["QtyOrder"]);

                    //CONVERTED ORDER/REQUIREMENT
                    double _QUANTITY_ORDER = Convert.ToDouble(oRow["QtyOrder"]) * Convert.ToDouble(oRow["CQtyOrder"]);
                    double _QUANTITY_ORDER_STATIC = Convert.ToDouble(oRow["QtyOrder"]) * Convert.ToDouble(oRow["CQtyOrder"]);
                    double _QUANTITY_DELIVERED = 0;
                    ItemManager _item_Mngr = new ItemManager();

                    _item_Mngr.Connection = oStockManager.Connection;

                    bool IsSalesItem = _item_Mngr.IsSalesItem(oRow["ItemCode"].ToString());
                    bool IsInventoryItem = _item_Mngr.IsInventoryItem(oRow["ItemCode"].ToString());

                    if (IsSalesItem == true && IsInventoryItem == true)
                    {

                        #region Rogemson Requirement
                        double _CURRENT_STOCK = 0;
                        //ben stock up need to re-read the logic code

                        foreach (DataRow _StockCardRow in _STOCK_CARD.Rows)
                        {

                            _CURRENT_STOCK = Convert.ToDouble(_StockCardRow["Qty"]);
                            
                            if (_CURRENT_STOCK >= _QUANTITY_ORDER)
                            {
                                //ben 10
                                _StockCardRow["Qty"] = Convert.ToDouble(_StockCardRow["Qty"]) - _QUANTITY_ORDER;
                                _QUANTITY_DELIVERED = _QUANTITY_DELIVERED + _QUANTITY_ORDER;
                                // Give a work around if Box
                                oRow["CQty"] = Convert.ToDouble(oRow["CQtyOrder"]);
                                oRow["Qty"] = Convert.ToDouble(oRow["QtyOrder"]);

                             
                                break;
                            }
                            else
                            {
                                double _OnlyAvailableQty = Convert.ToDouble(_StockCardRow["Qty"]);

                                _QUANTITY_DELIVERED = _QUANTITY_DELIVERED + _OnlyAvailableQty;
                                _StockCardRow["Qty"] = 0;

                                //oRow["Qty"] = (Convert.ToDouble(oRow["Qty"]) + _OnlyAvailableQty);
                                oRow["CQty"] = Convert.ToDouble(oRow["CQtyOrder"]);

                              

                                _QUANTITY_ORDER = _QUANTITY_ORDER - _OnlyAvailableQty;

                            }

                        }

                   

                        if (_QUANTITY_ORDER_STATIC != _QUANTITY_DELIVERED)
                        {
                           
                            oRow["Qty"] = 0;
                        }
                        else
                        {
                            if (_PackSize > 1)
                            {
                                oRow["Qty"] = _QUANTITY_DELIVERED / _PackSize;
                            }
                        }


                        #endregion

                    }
                    else
                    {
                        gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["QtyServed"], 0);
                        gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Amount"], 0);
                    }

                    double _QUANTITY_CONV = Convert.ToDouble(oRow["CQty"]);
                    double _QUANTITY = Convert.ToDouble(oRow["Qty"]);
                    double _UNITPRICE = Convert.ToDouble(oRow["UnitPrice"]);
                    double _TOTAL_DISCOUNT = _QUANTITY * Convert.ToDouble(oRow["Discount"]);

                    double _AMOUNT = ((_QUANTITY * _QUANTITY_CONV) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    bool IsFree = false;
                    try
                    {
                        IsFree = Convert.ToBoolean(oRow["IsFree"]);
                    }
                    catch
                    {
                        IsFree = false;
                    }

                    if (!IsFree)
                    {
                        oRow["TotalLineDisc"] = _TOTAL_DISCOUNT;
                        oRow["Amount"] = _AMOUNT;
                    }
                    else
                    {
                        double _ZeroDiscount = 0;
                        double _ZeroAmount = 0;

                        oRow["TotalLineDisc"] = _ZeroDiscount;
                        oRow["Amount"] = _ZeroAmount;
                    }
                    oStockManager.Close();

                }
                #endregion

                ComputeTotal();
                ApplyVolumeDiscount();


            }
            else 
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Please select customer first!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Please select customer first!!!", "Card Code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
            }
        }

        private void txtReference_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

            }
        }

        private void txtQtyServed_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtStatus.Text == "Posted" || txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                return;
            }
            int iFocusRowHandle = gridViewDRItems.FocusedRowHandle;

            string sItemCode = gridViewDRItems.GetRowCellValue(iFocusRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();

            bool IsSalesItem = false;
            bool IsInventoryItem = false;

            ItemManager oManager = new ItemManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            IsSalesItem = oManager.IsSalesItem(sItemCode);
            IsInventoryItem = oManager.IsInventoryItem(sItemCode);

            if (IsSalesItem == true && IsInventoryItem == true)
            {
                GetStocksForDeliver oForm = new GetStocksForDeliver();
                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;
                if (cboLocation.EditValue != null)
                {

                    oForm.ConnectionString = this.ConnectionString;

                    int iCount = -1;
                    int[] oRow = gridViewDRItems.GetSelectedRows();

                    iCount = oRow[0];
                    oForm.ItemGuID = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemGuID"]).ToString();
                    oForm.ItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                    oForm.ItemName = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemDesc"]).ToString();
                    oForm.UoM = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UoM"]).ToString();

                    double _OrderQty = 0;
                    double _OrderPacksize = 0;

                    try
                    {
                        _OrderQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["QtyOrder"]).ToString());
                    }
                    catch
                    {
                        _OrderQty = 0;
                    }

                    try
                    {
                        _OrderPacksize = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQtyOrder"]).ToString());
                    }
                    catch
                    {
                        _OrderPacksize = 0;
                    }

                    if (_OrderQty != 0)
                    {
                        oForm.OrderQty = _OrderQty.ToString();
                        oForm.PackSize = _OrderPacksize.ToString();
                    }
                    else
                    {
                        oForm.OrderQty = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString();
                        oForm.PackSize = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString();
                    }


                    oForm.ServedQty = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString();
                    oForm.ServedPackSize = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString();


                    oForm.WhsName = cboLocation.Text;
                    oForm.WhsCode = cboLocation.EditValue.ToString();

                    oForm.ShowDialog();

                    gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Qty"], Convert.ToDouble(oForm.TotalServed));
                    if (oForm.PackSize != "")
                    {
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["CQty"], Convert.ToDouble(oForm.PackSize));
                    }
                    else
                    {
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["CQty"], 1);
                        oForm.PackSize = "1";
                    }
                    double _QUANTITY = Convert.ToDouble(oForm.TotalServed);
                    double _CQUANTITY = Convert.ToDouble(oForm.PackSize);
                    double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                    double _DISCOUNT_PERCENT = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["DiscPrcnt"]).ToString()) / 100;

                    double _DISCOUNT_AMOUNT = Convert.ToDouble((_UNITPRICE * _DISCOUNT_PERCENT).ToString("###.0000"));
                    gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Discount"], _DISCOUNT_AMOUNT);
                    double _TOTAL_DISCOUNT = Convert.ToDouble(((_QUANTITY * _CQUANTITY) * _DISCOUNT_AMOUNT).ToString("###.0000"));

                    double _AMOUNT = Convert.ToDouble((((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT).ToString("###.0000"));
                    bool IsFree = false;
                    try
                    {
                        IsFree = Convert.ToBoolean(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["IsFree"]));
                    }
                    catch
                    {
                        IsFree = false;
                    }

                    if (!IsFree)
                    {
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _AMOUNT);
                    }
                    else
                    {
                        double _ZeroDiscount = 0;
                        double _ZeroAmount = 0;

                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _ZeroDiscount);
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _ZeroAmount);
                    }

                    ComputeTotal();
                    ApplyVolumeDiscount();

                }
                else
                {
                    MainMenu oMainForm = (MainMenu)this.MdiParent;

                    oMainForm.ErrMsg.ImageIndex = 6;
                    oMainForm.ErrMsg.Caption = "Please select warehouse.";
                    oMainForm.timer1.Enabled = true;
                    //MessageBox.Show("Please select warehouse.", "Warehouse", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else if(IsInventoryItem == false && IsSalesItem==true)
            {
                GetStocksWithBOM oForm = new GetStocksWithBOM();
                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;
                if (cboLocation.EditValue != null)
                {

                    oForm.ConnectionString = this.ConnectionString;

                    int iCount = -1;
                    int[] oRow = gridViewDRItems.GetSelectedRows();

                    iCount = oRow[0];

                    oForm.PriceListCode = this.DefaultPriceList;
                    oForm.ItemGuID = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemGuID"]).ToString();
                    oForm.ItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                    oForm.ItemName = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemDesc"]).ToString();
                    oForm.UoM = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UoM"]).ToString();
                    oForm.OrderQty = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["QtyOrder"]).ToString();

                    oForm.WhsName = cboLocation.Text;
                    oForm.WhsCode = cboLocation.EditValue.ToString();

                    oForm.ShowDialog();

                    gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Qty"], oForm.TotalServed);
                    gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["CQty"], oForm.PackSize);
                    double _QUANTITY = Convert.ToDouble(oForm.TotalServed);
                    double _CQUANTITY = Convert.ToDouble(oForm.PackSize);
                    

                    double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    bool IsFree = false;
                    try
                    {
                        IsFree = Convert.ToBoolean(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["IsFree"]));
                    }
                    catch
                    {
                        IsFree = false;
                    }

                    if (!IsFree)
                    {
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _AMOUNT);
                    }
                    else
                    {
                        double _ZeroDiscount = 0;
                        double _ZeroAmount = 0;

                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _ZeroDiscount);
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _ZeroAmount);
                    }

                    ComputeTotal();
                    ApplyVolumeDiscount();

                }
                else
                {
                    MainMenu oMainForm = (MainMenu)this.MdiParent;

                    oMainForm.ErrMsg.ImageIndex = 6;
                    oMainForm.ErrMsg.Caption = "Please select warehouse.";
                    oMainForm.timer1.Enabled = true;
                    //MessageBox.Show("Please select warehouse.", "Warehouse", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

        }

        private void txtQtyServed_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    
                    int iCount = gridViewDRItems.FocusedRowHandle;
                    bool IsFree = Convert.ToBoolean(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["IsFree"]));

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQTY"]).ToString());
                    
                    string _ITEMCODE = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;

                    if (IsFree == false)
                    {
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _AMOUNT);
                    }
                    else
                    {
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], 0);
                        gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], 0);
                    }
                    ComputeTotal();
                    ApplyVolumeDiscount();
                }
                catch
                {
                }
            }
        }

        private void txtQtyServed_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                
                    int iCount = -1;
                    int[] oRow = gridViewDRItems.GetSelectedRows();
                    iCount = oRow[0];

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString());

                    string _ITEMCODE = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;

                    gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _AMOUNT);

                    ComputeTotal();
                    ApplyVolumeDiscount();


                    if (_QUANTITY == 0)
                    {
                        oTextQty.BackColor = Color.Yellow;
                    }
            }
            catch
            {
            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
           

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = true;
                addRowToolStripMenuItem.Enabled = true;
                deleteRowToolStripMenuItem.Enabled = true;
                btnCopyToSR.Visible = false;
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed" || txtStatus.Text == "In-Process")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
                btnCopyToSR.Visible = false;
                btnCopyInvoice.Visible = false;
            }

            if (txtStatus.Text == "Delivered")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();

                btnAdd.Enabled = true;
                btnAdd.Text = "Update";
                txtRefDoc.Enabled = true;

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;

                btnCopyToSR.Visible = true;
                
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;

                btnCopyToSR.Visible = true;
                btnCopyInvoice.Visible = true;
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;

                btnCopyToSR.Visible = false;
                btnCopyInvoice.Visible = true;
            }
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            SalesDelivery_Resize(sender, e);
            if (txtDocumentNumber.Text != "##########")
            {
                if (txtStatus.Text == "Draft" )
                {
                   
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        ChangeToDeliverStatus(txtDocumentNumber.Text);
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                }
                else if (txtStatus.Text == "Delivered")
                {

                 
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        ChangeToPostedStatus(txtDocumentNumber.Text);
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                  
                }
                else
                {

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        
                        ChangeToClosedStatus(txtDocumentNumber.Text);
                    }
                }
            }
            
        }

        private void txtReference_EditValueChanged(object sender, EventArgs e)
        {
            if (txtReference.Text.Trim() != "")
            {
                txtDisc1.Properties.ReadOnly = true;
                txtDisc2.Properties.ReadOnly = true;
                txtDisc3.Properties.ReadOnly = true;
                txtDisc4.Properties.ReadOnly = true;
                txtTotalDiscount.Properties.ReadOnly = true;
            }
            else
            {
                txtDisc1.Properties.ReadOnly = false;
                txtTotalDiscount.Properties.ReadOnly = false;
            }
        }

        private void dtPostDate_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }

            try
            {
                dtDeliveryDate.Properties.MinValue = (DateTime)dtPostDate.EditValue;
                dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));
            }
            catch { }
        }

        private void txtCardCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {

             
                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.SearchIndex = 0;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.ShowDialog();

                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address.Trim();
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.VATCode = _SearchBP.VATCode;
                txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                txtDivision.Text = _SearchBP.Division;
                cboDocument.EditValue = _SearchBP.Document;
                this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                try
                {
                    cboDocument.Text = _SearchBP.Document;  //oRow["Documnt"].ToString();
                }
                catch
                {
                }

                try
                {
                    txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                    txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                    txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                    txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                }
                catch
                {
                }
                dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));
                //cboCurrency.Text 


                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

                if (this.VATCode != "NON-VAT")
                {
                    lblVAT.Visible = true;
                    txtVAT.Visible = true;

                    lblTotalLineDiscount.Top = 426;
                    txtTotalLineDiscount.Top = 426;

                    lblDiscount.Top = 456;
                    txtDisc1.Top = 456;
                    txtDisc2.Top = 456;
                    txtDisc3.Top = 456;
                    txtDisc4.Top = 456;
                    txtTotalDiscount.Top = 456;

                    lblNetAmt.Top = 484;
                    txtNetAmt.Top = 484;


                }
                else
                {
                    lblVAT.Visible = false;
                    txtVAT.Visible = false;

                    lblTotalLineDiscount.Top = lblTotalLineDiscount.Top - 26;
                    txtTotalLineDiscount.Top = txtTotalLineDiscount.Top - 26;

                    lblDiscount.Top = lblDiscount.Top - 26;

                    txtDisc1.Top = txtDisc1.Top - 26;
                    txtDisc2.Top = txtDisc2.Top - 26;
                    txtDisc3.Top = txtDisc3.Top - 26;
                    txtDisc4.Top = txtDisc4.Top - 26;
                    txtTotalDiscount.Top = txtTotalDiscount.Top - 26;

                    lblNetAmt.Top = lblNetAmt.Top - 26;
                    txtNetAmt.Top = txtNetAmt.Top - 26;

                }

                oTxManager.Close();

                if (_SearchBP.BuyerSalesMan != "")
                {
                    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                }

                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void txtCardCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByBPCode(txtCardCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByBPCode(txtCardCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();

                    txtDivision.Text = oRow["Division"].ToString();
                    try
                    {
                        cboDocument.Text = oRow["Documnt"].ToString();
                    }
                    catch 
                    { 
                    }
                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void txtLineDiscPercent_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridViewDRItems.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt / 100);
                double _TotalDiscount = (_Qty * _CQty) * _LineDiscount;

                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Discount"], _LineDiscount);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;

                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _Amount);

                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }
        }

        private void btnSearchItemCode_Leave(object sender, EventArgs e)
        {
            #region Old Code
            //string _ItemGUID = System.Guid.NewGuid().ToString();

            //DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

            //try
            //{
            //    string sItemCode = oButtonEdit.Text;
            //    ItemManager oManager = new ItemManager();

            //    oManager.ConnectionString = this.ConnectionString;
            //    oManager.Open();

            //    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

            //    oManager.Close();

            //    if (dt.Rows.Count > 0)
            //    {
            //        #region If Has Rows
            //        var items = from row in dt.AsEnumerable()
            //                    select new
            //                    {
            //                        ItemCode = row["ItemCode"].ToString(),
            //                        Dscription = row["Description"].ToString(),
            //                        UoM = row["UNITOFMEASURE"].ToString(),
            //                        UnitPrice = row["UNITPRICE"].ToString()
            //                    };


            //        int iCount = -1;
            //        int[] oRow = gridView1.GetSelectedRows();

            //        iCount = oRow[0];

            //        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
            //        double _ZeroVAL = 0;
            //        int iRowIndex = gridView1.FocusedRowHandle;

            //        if (iRowIndex < 0)
            //        {
            //            iRowIndex = 0;
            //        }
            //        foreach (var oUnit in items)
            //        {
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGUID);
            //        }
            //        #endregion


            //        #region Applying in Line Item Amount Computation
            //        double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
            //        double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

            //        double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
            //        gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
            //        gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
            //        ComputeTotal();
            //        ApplyVolumeDiscount();
            //        #endregion
            //    }
            //    else
            //    {
            //        MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        oButtonEdit.Text = "";
            //        oButtonEdit.Focus();
            //    }
            //}
            //catch
            //{
            //}
            #endregion

         
        }

        private void xtrInvoiceScrollable_Click(object sender, EventArgs e)
        {

        }

        private void gridViewDR_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")

                e.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void SalesDelivery_Shown(object sender, EventArgs e)
        {
            SalesDelivery_Resize(sender, e);
            gridDRItems.Select();
            gridViewDRItems.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridViewDRItems.FocusedColumn = gridViewDRItems.Columns["ItemCode"];
            gridViewDRItems.ShowEditor();

            

            txtCardCode.Focus();


            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }

        }

        private void cboUnitMeasure_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.ComboBoxEdit oCboUoM = (DevExpress.XtraEditors.ComboBoxEdit)sender;
            string sUoM = "";
            try
            {
                sUoM = Convert.ToString(oCboUoM.Text);
            }
            catch
            {
                sUoM = "";
            }
            if (sUoM != "")
            {
                gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["UoM"], sUoM);
            }
        }

        private void cboUnitMeasure_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sItemCode = "";
            string sUoM = "";

            int iFocusRowHandle = gridViewDRItems.FocusedRowHandle;

            try
            {
                sItemCode = gridViewDRItems.GetRowCellValue(iFocusRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();

                DevExpress.XtraEditors.ComboBoxEdit oCombo = (DevExpress.XtraEditors.ComboBoxEdit)sender;

                sUoM = oCombo.Text;

                UoMManager oManager = new UoMManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                double _PackSize = oManager.GetPackSize(sItemCode, sUoM);
                oManager.Close();

                gridViewDRItems.SetRowCellValue(iFocusRowHandle, gridViewDRItems.Columns["CQty"], _PackSize);



                int iCount = -1;
                int[] oRow = gridViewDRItems.GetSelectedRows();
                iCount = oRow[0];

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Qty"]).ToString());
                double _CQUANTITY = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["CQty"]).ToString());
                string _ITEMCODE = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["Amount"], _AMOUNT);
                bool IsChecked = false;
                gridViewDRItems.SetRowCellValue(iCount, gridViewDRItems.Columns["IsFree"], IsChecked);
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }

        }

        private void SalesDelivery_Resize(object sender, EventArgs e)
        {
            if (this.Width > 863)
            {
                #region Upper Part Objects
                lblDocNo.Left = this.Width - 336;
                txtDocumentNumber.Left = this.Width - 173;

                lblDocStatus.Left = this.Width - 336;
                txtStatus.Left = this.Width - 173;

                lblDeliveryDate.Left = this.Width - 336;
                dtPostDate.Left = this.Width - 173;

                lblValidUntilDeliveryDate.Left = this.Width - 336;
                dtDeliveryDate.Left = this.Width - 173;

                lblInvoiceDate.Left = this.Width - 336;
                dtDocDate.Left = this.Width - 173;

                lblSeries.Left = this.Width - 336;
                cboDocument.Left = this.Width - 276;

                txtRefDoc.Left = this.Width - 173;
                #endregion

                gridDRItems.Width = this.Width - 56;


                #region Lower Part Objects
                lblGrossAmount.Left = this.Width - 443;
                txtGrossAmount.Left = this.Width - 336;

                lblTotalLineDiscount.Left = this.Width - 443;
                txtTotalLineDiscount.Left = this.Width - 336;

                lblDiscount.Left = this.Width - 443;
                txtDisc1.Left = this.Width - 336;
                txtDisc2.Left = this.Width - 284;
                txtDisc3.Left = this.Width - 229;
                txtDisc4.Left = this.Width - 174;
                txtTotalDiscount.Left = this.Width - 119;

                lblVAT.Left = this.Width - 443;
                txtVAT.Left = this.Width - 336;


                lblNetAmt.Left = this.Width - 443;
                txtNetAmt.Left = this.Width - 336;

                lblWithHoldingTax.Left = this.Width - 229;
                txtWithHoldingTax.Left = this.Width - 119;
                #endregion
            }
            else
            {
                
                lblDocNo.Left = 542;
                txtDocumentNumber.Left = 704;

                lblDocStatus.Left = 542;
                txtStatus.Left = 704;

                lblDeliveryDate.Left = 542;
                dtPostDate.Left = 704;

                lblValidUntilDeliveryDate.Left = 542;
                dtDeliveryDate.Left = 704;

                lblInvoiceDate.Left = 542;
                dtDocDate.Left = 704;

                lblSeries.Left = 542;
                cboDocument.Left = 601;
                
                txtRefDoc.Left = 704;

                gridDRItems.Width = 817;

                lblGrossAmount.Left = 434;
                lblTotalLineDiscount.Left = 434;

                txtGrossAmount.Left = 542;
                txtTotalLineDiscount.Left = 542;
                lblDiscount.Left = 434;
                txtDisc1.Left = 542;
                txtDisc2.Left = 594;
                txtDisc3.Left = 649;
                txtDisc4.Left = 704;
                txtTotalDiscount.Left = 759;

                lblVAT.Left = 434;
                txtVAT.Left = 542;

                lblNetAmt.Left = 434;
                txtNetAmt.Left = 542;

                lblWithHoldingTax.Left = 649;

                txtWithHoldingTax.Left = 759;

            }


            if (this.Height > 543)
            {
                gridDRItems.Height = this.Height - 359;

                lblSalesMan.Top = this.Height - 166;
                cboSalesman.Top = this.Height - 166;

                lblRemarks.Top = this.Height - 140;
                txtRemarks.Top = this.Height - 140;

                btnCopyInvoice.Top = this.Height - 67;
                btnCopyToSR.Top = this.Height - 67;
                btnAdd.Top = this.Height - 67;
                btnCancel.Top = this.Height - 67;

                lblGrossAmount.Top = this.Height - 166;
                txtGrossAmount.Top = this.Height - 166;

                lblTotalLineDiscount.Top = this.Height - 139;
                txtTotalLineDiscount.Top = this.Height - 139;

                lblDiscount.Top = this.Height - 113;
                txtDisc1.Top = this.Height - 113;
                txtDisc2.Top = this.Height - 113;
                txtDisc3.Top = this.Height - 113;
                txtDisc4.Top = this.Height - 113;

                txtTotalDiscount.Top = this.Height - 113;
                lblVAT.Top = this.Height - 88;
                txtVAT.Top = this.Height - 88;

                lblNetAmt.Top = this.Height - 61;
                txtNetAmt.Top = this.Height - 61;


                lblWithHoldingTax.Top = this.Height - 85;
                txtWithHoldingTax.Top = this.Height - 85;


            }
            else
            {
                gridDRItems.Height = 184;

                lblSalesMan.Top = 377;
                cboSalesman.Top = 377;

                lblRemarks.Top = 403;
                txtRemarks.Top = 403;

                btnCopyInvoice.Top = 476;
                btnCopyToSR.Top = 476;
                btnAdd.Top = 476;
                btnCancel.Top = 476;

                lblGrossAmount.Top = 377;
                txtGrossAmount.Top = 377;

                lblTotalLineDiscount.Top = 404;
                txtTotalLineDiscount.Top = 404;

                lblDiscount.Top = 430;
                txtDisc1.Top = 430;
                txtDisc2.Top = 430;
                txtDisc3.Top = 430;
                txtDisc4.Top = 430;
                txtTotalDiscount.Top = 430;

                lblVAT.Top = 455;
                txtVAT.Top = 455;

                lblNetAmt.Top = 482;
                txtNetAmt.Top = 482;


                lblWithHoldingTax.Top =458;
                txtWithHoldingTax.Top = 458;
            }
        }

        private void gridDR_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                cntxtRightClickMenu.Show(Cursor.Position);
            }
        }

        private void addRowToolStripMenuItem_Click(object sender, EventArgs e)
        {


            if (gridViewDRItems.IsLastRow == false)
            {
                gridViewDRItems.MoveLast();
            }

            string _ItemCode = "";

            _ItemCode = gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();

            if (_ItemCode.Trim() == "")
            {
                MessageBox.Show("New row is already exists!!!", "Add Row", MessageBoxButtons.OK, MessageBoxIcon.Information);

                gridViewDRItems.MoveLast();
                gridViewDRItems.FocusedColumn = gridViewDRItems.Columns["ItemCode"];
                gridViewDRItems.ShowEditor();
            }
            else
            {
                gridViewDRItems.AddNewRow();

                txtCardCode.Focus();

                gridDRItems.Select();
                gridViewDRItems.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                gridViewDRItems.FocusedColumn = gridViewDRItems.VisibleColumns[1];
                gridViewDRItems.ShowEditor();
            }
        }

        private void insertNewRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iRowHandle = gridViewDRItems.FocusedRowHandle;

            DataTable dt = this.DeliveryLineItems;
            DataRow _BlankRow = dt.NewRow();

            dt.Rows.InsertAt(_BlankRow, iRowHandle);

            gridDRItems.DataSource = dt;
            gridDRItems.Refresh();

            gridViewDRItems.FocusedRowHandle = iRowHandle;
        }

        private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iCount = gridViewDRItems.FocusedRowHandle;


            if (txtStatus.Text == "Draft")
            {
                if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {

                    if (gridViewDRItems.IsLastRow)
                    {
                        string sItemCode = "";


                        iCount = gridViewDRItems.FocusedRowHandle;
                        sItemCode = gridViewDRItems.GetRowCellValue(iCount, gridViewDRItems.Columns["ItemCode"]).ToString();


                        if (sItemCode != "")
                        {
                            gridViewDRItems.DeleteRow(iCount);
                            gridViewDRItems.AddNewRow();
                        }


                        gridViewDRItems.RefreshData();

                    }
                    else
                    {


                        iCount = gridViewDRItems.FocusedRowHandle;

                        gridViewDRItems.DeleteRow(iCount);
                        gridViewDRItems.RefreshData();
                    }

                    ComputeTotal();
                }
            }
                 
        }

        private void txtStoreCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {

                

                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.SearchIndex = 2;
                _SearchBP.ShowDialog();

                txtStoreCode.Text = _SearchBP.StoreCode;
                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address;
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.VATCode = _SearchBP.VATCode;
                txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                txtDivision.Text = _SearchBP.Division;
                cboDocument.EditValue = _SearchBP.Document;


                try
                {
                    txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                    txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                    txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                    txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                }
                catch
                {
                }
                dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));
                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

                if (this.VATCode != "NON-VAT")
                {
                    lblVAT.Visible = true;
                    txtVAT.Visible = true;

                    lblTotalLineDiscount.Top = 426;
                    txtTotalLineDiscount.Top = 426;

                    lblDiscount.Top = 456;
                    txtDisc1.Top = 456;
                    txtDisc2.Top = 456;
                    txtDisc3.Top = 456;
                    txtDisc4.Top = 456;
                    txtTotalDiscount.Top = 456;

                    lblNetAmt.Top = 484;
                    txtNetAmt.Top = 484;


                }
                else
                {
                    lblVAT.Visible = false;
                    txtVAT.Visible = false;

                    lblTotalLineDiscount.Top = lblTotalLineDiscount.Top - 26;
                    txtTotalLineDiscount.Top = txtTotalLineDiscount.Top - 26;

                    lblDiscount.Top = lblDiscount.Top - 26;

                    txtDisc1.Top = txtDisc1.Top - 26;
                    txtDisc2.Top = txtDisc2.Top - 26;
                    txtDisc3.Top = txtDisc3.Top - 26;
                    txtDisc4.Top = txtDisc4.Top - 26;
                    txtTotalDiscount.Top = txtTotalDiscount.Top - 26;

                    lblNetAmt.Top = lblNetAmt.Top - 26;
                    txtNetAmt.Top = txtNetAmt.Top - 26;

                }

                oTxManager.Close();

                if (_SearchBP.BuyerSalesMan != "")
                {
                    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                }

                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void txtStoreCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByStoreCode(txtStoreCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.SearchIndex = 2;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByStoreCode(txtStoreCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();

                    txtDivision.Text = oRow["Division"].ToString();
                    try
                    {
                        cboDocument.Text = oRow["Documnt"].ToString();
                    }
                    catch
                    {
                    }
                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void btnCopyToSR_Click(object sender, EventArgs e)
        {
            SalesReturn oForm = new SalesReturn();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ActiveUserID = this.ActiveUserID;
            oForm.DefaultWarehouse = this.DefaultWarehouse;
            oForm.IsMultipleWarehouse = this.IsMultipleWarehouse;
            oForm.ReferenceSINo = "";
            oForm.MdiParent = this.MdiParent;
            oForm.CopyDeliveryToReturn(txtDocumentNumber.Text);

            oForm.Show();
        }

        private void distributionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InvoiceDistribution oForm = new InvoiceDistribution();

            oForm.ConnectionString = this.ConnectionString;
            oForm.DocumentNumber = txtDocumentNumber.Text;

            oForm.ShowDialog();
        }

        private void duplicateToolMenu_Click(object sender, EventArgs e)
        {
            EnableControls();
            InitializeSeries();
            btnAdd.Text = "Add";
            txtStatus.Text = "Draft";
            btnCopyToSR.Visible = false;
        }

        private void txtCardCode_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboLocation_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtCustRefPO_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtDivision_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtShipTo_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboDocument_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRefDoc_EditValueChanged(object sender, EventArgs e)
        {
            txtRefDoc.BackColor = System.Drawing.Color.Empty;
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboSalesman_EditValueChanged_1(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRemarks_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtDeliveryDate_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtDocDate_EditValueChanged(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Ok" && (txtStatus.Text == "Draft" || txtStatus.Text == "Delivered"))
            {
                btnAdd.Text = "Update";
            }
        }

        private void btnCopyInvoice_Click(object sender, EventArgs e)
        {
            SalesInvoice oForm = new SalesInvoice();

            oForm.ConnectionString = this.ConnectionString;
            oForm.IsMultipleWarehouse = this.IsMultipleWarehouse;
            oForm.DefaultWarehouse = this.DefaultWarehouse;
            oForm.DefaultPriceList = this.DefaultPriceList;
            oForm.ActiveUserID = this.ActiveUserID;
            oForm.MdiParent = this.MdiParent;

            oForm.CopyDRToInvoice(txtDocumentNumber.Text);

            oForm.Show();
        }
        
        private void gridViewDR_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridViewDRItems.FocusedColumn == gridViewDRItems.Columns["LotNumber"])
            {
                BindLotNumber(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString(), cboLotNumber);
            }
        }

        private void gridViewDR_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        {
            if (e.FocusedColumn == gridViewDRItems.Columns["LotNumber"])
            {
                BindLotNumber(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString(), cboLotNumber);
            }
        }

        private void cboLotNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            double iPackSize = 1;

            CNotebook.Inventory.UoMManager unitMeasureManager = new UoMManager();

            string _WarehouseCode = cboLocation.EditValue.ToString();
            string _ItemCode = gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();
            string _unitMeasure = gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["UoM"]).ToString();
            string _LotNumber = ((DevExpress.XtraEditors.ComboBoxEdit)sender).EditValue.ToString();

            unitMeasureManager.ConnectionString = this.ConnectionString;
            unitMeasureManager.Open();

            iPackSize = unitMeasureManager.GetPackSize(_ItemCode, _unitMeasure);

            unitMeasureManager.Close();

            gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["LotNumber"], _LotNumber);
            gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["CQty"], iPackSize);




            StockManager oManager = new StockManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            double _OrderQty = Convert.ToDouble(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["QtyOrder"]));
            double _OnStockQty = oManager.GetAvailableQuantity(_WarehouseCode, _ItemCode, _LotNumber);
            double _UnitCost = oManager.GetUnitCost(_WarehouseCode, _ItemCode, _LotNumber);

            if (_OnStockQty < _OrderQty)
            {
                MessageBox.Show("You have insufficient stock quantity!!! Please check your current stock before proceeding!!!", "Stock", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }

            gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["LastStockQty"], _OnStockQty);
            if (iPackSize == 0)
            {
                gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Qty"], _OnStockQty);
            }
            else
            {
                gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Qty"], _OnStockQty/iPackSize);
            }
            gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["UnitCost"], _UnitCost);

            gridViewDRItems.FocusedColumn = gridViewDRItems.Columns["Qty"];
            gridViewDRItems.ShowEditor();

            oManager.Close();
        }

        private void txtQtyServed_EditValueChanged_1(object sender, EventArgs e)
        {
            try
            {
                bool IsFree = Convert.ToBoolean(gridViewDRItems.GetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["IsFree"]));
                
                gridViewDRItems.SetRowCellValue(gridViewDRItems.FocusedRowHandle, gridViewDRItems.Columns["Qty"], Convert.ToDouble(((DevExpress.XtraEditors.TextEdit)sender).EditValue.ToString()));

                double _EnteredQty = Convert.ToDouble(((DevExpress.XtraEditors.TextEdit)sender).EditValue.ToString());


                int iFocusedRowHandle = gridViewDRItems.FocusedRowHandle;

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                double _CQUANTITY = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["CQty"]).ToString());

                string _ITEMCODE = gridViewDRItems.GetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(gridViewDRItems.GetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridViewDRItems.GetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;

                
                if (IsFree == false)
                {
                    gridViewDRItems.SetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridViewDRItems.SetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["Amount"], _AMOUNT);
                }
                else
                {
                    gridViewDRItems.SetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["TotalLineDisc"], 0);
                    gridViewDRItems.SetRowCellValue(iFocusedRowHandle, gridViewDRItems.Columns["Amount"], 0);
                }

                ComputeTotal();
                ApplyVolumeDiscount();


                if (_QUANTITY == 0)
                {
                    oTextQty.BackColor = Color.Yellow;
                    return;
                }
            }
            catch
            {
                return;
            }
        }

        private void cboLotNumber_EditValueChanged(object sender, EventArgs e)
        {
            //gridViewDR.SetRowCellValue(gridViewDR.FocusedRowHandle, gridViewDR.Columns["LotNumber"], ((DevExpress.XtraEditors.ComboBoxEdit)sender).Text);
        }

        private void gridDR_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void tabDetails_Paint(object sender, PaintEventArgs e)
        {

        }

        private void txtQtyServed_Leave(object sender, EventArgs e)
        {
            gridViewDRItems.FocusedColumn = gridViewDRItems.Columns["PackSize"];
        }
        #endregion

        private void barAddNewEntry_ItemClick(object sender, ItemClickEventArgs e)
        {
            int iRowIndex = gridViewDRAcctEntries.RowCount;
            if (gridViewDRAcctEntries.RowCount <= 0)
            {
                gridViewDRAcctEntries.AddNewRow();
                return;
            }
            gridViewDRAcctEntries.FocusedRowHandle = iRowIndex - 1;
            try
            {
             
                string _AcctCode = "";


                if (gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]) != null)
                {
                    _AcctCode = gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]).ToString();
                }
                else
                {
                    _AcctCode = "";
                }

                if (_AcctCode.Trim() == "")
                {
                    return;
                }
            }
            catch { }

            gridViewDRAcctEntries.AddNewRow();

           
        }

        private void barClear_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.AccountingEntries = GetGLAcctStructure();

            gridDRAcctEntries.DataSource = this.AccountingEntries;
            gridDRAcctEntries.Refresh();
        }

        private void barSaveARDistribution_ItemClick(object sender, ItemClickEventArgs e)
        {
            DeliveryManager oManager = new DeliveryManager();

            RemoveBlankLastGLAccounts();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

                SqlException ex = oManager.AddDistributionEntries(this.txtDocumentNumber.Text, this.AccountingEntries);

                if (ex != null)
                {
                    MessageBox.Show(ex.Message.ToString(), "Error Saving", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Accounting is successfully saved!!!", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            
            oManager.Close();
        }

        private void barPostEntries_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void txtAcctCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();

            gridViewDRAcctEntries.SetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"], oForm.SelectedGLAcctCode);
            gridViewDRAcctEntries.SetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctName"], oForm.SelectedGLAcctName);

        }

        private void grdViewDREntries_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]).ToString().Trim() != "")
                {
                    if (MessageBox.Show("Are you sure you want to delete this item?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        
                        gridViewDRAcctEntries.DeleteRow(gridViewDRAcctEntries.FocusedRowHandle);
                    }
                }
            }
            
            if (e.KeyCode == Keys.Down)
            {
                int iRowIndex = gridViewDRAcctEntries.FocusedRowHandle;
                if (gridViewDRAcctEntries.RowCount <= 0)
                {
                    gridViewDRAcctEntries.AddNewRow();
                    return;
                }
                gridViewDRAcctEntries.FocusedRowHandle = iRowIndex;

                if (gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]).ToString().Trim() != "" || gridViewDRAcctEntries.GetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"]) !=null)
                {
                    gridViewDRAcctEntries.AddNewRow();
                    return;
                }

            }
        }

        private void txtAcctCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_ACCOUNTCODE = (DevExpress.XtraEditors.TextEdit)sender;

                ChartOfAccountManager oManager = new ChartOfAccountManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = oManager.GetChartOfAccountByAcctCode(_TEXT_ACCOUNTCODE.Text);
                oManager.Close();


                if (dt.Rows.Count > 0)
                {
                    DataRow oRow = dt.Rows[0];

                    string sAcctCode = oRow["AcctCode"].ToString();
                    string sAcctName = oRow["AcctName"].ToString();
                    gridViewDRAcctEntries.SetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"], sAcctCode);
                    gridViewDRAcctEntries.SetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctName"], sAcctName);


                }

                else
                {

                    FND_GLACCOUNT oForm = new FND_GLACCOUNT();

                    DevExpress.XtraEditors.TextEdit eGLAccount = (DevExpress.XtraEditors.TextEdit)sender;

                    oForm.ConnectionString = this.ConnectionString;
                    oForm.SetSearch(eGLAccount.Text);
                    oForm.ShowDialog();

                    gridViewDRAcctEntries.SetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctCode"], oForm.SelectedGLAcctCode);
                    gridViewDRAcctEntries.SetRowCellValue(gridViewDRAcctEntries.FocusedRowHandle, gridViewDRAcctEntries.Columns["AcctName"], oForm.SelectedGLAcctName);

                }
                //grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["Particulars"];

            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void barClearEntries_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (gridViewDRAcctEntries.RowCount <= 0)
            {
                MessageBox.Show("There was no GL Account entries in Grid.", "Clear GL Entries", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show("Are you sure you want to clear all entries made?", "Clear GL Entries", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {

                this.AccountingEntries = GetGLAcctStructure();

                gridDRAcctEntries.DataSource = this.AccountingEntries;
                gridDRAcctEntries.Refresh();
            }
        }

        private void barSettings_ItemClick(object sender, ItemClickEventArgs e)
        {
            NotebookS2.Sales.Settings.DRSettings oForm = new Sales.Settings.DRSettings();

            oForm.ShowDialog();
        }

        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }

      
        
    }
}
